<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src="">
        
        
        
        const arr = [
    {id: 1, pid: 0, title: "首页"},
    {id: 2, pid: 1, title: "订单列表"},
    {id: 3, pid: 1, title: "刊登管理"},
    {id: 4, pid: 3, title: "刊登列表"},
    {id: 5, pid: 3, title: "刊登设置"},
    {id: 6, pid: 0, title: "登陆"},
]
// 1、修改数组：
function getList(arry) {
    const data = [];
    function _getParent(list, pid = 1) {
        for(let i=0;i<list.length;i++){
            if(list[i].id === pid){
                parent = list[i];break;
            }
            else{
                if(list[i].children.length>0)
                    _getParent(list[i].children,pid)
            }
        }
        return parent;
    }
    arry.forEach(v => {
        v.children = [];
        if (v.pid === 0) {
            data.push(v);
        } else {
            let parent = _getParent(data,v.pid);
            parent.children.push(v);
        }
    })
    return data;
}
const list = getList(arr);

// 2、实现方法通过输入id，得到title的数组，例如：getTitle(5)// [ '首页', '刊登管理', '刊登设置' ]
function getTitles(id){
    function _getTileArr(list, id = 1,titleArr=[]) {

        let parent ={};
        for(let i=0;i<list.length;i++){
            if(list[i].id === id){
                parent = list[i];
                titleArr.push(parent.title);
                break;
            }
            else{
                if(list[i].children.length>0){
                    titleArr.push(list[i].title);
                    _getTileArr(list[i].children,id,titleArr)
                }

            }
        }
        return titleArr;
    }
    return _getTileArr(list,id);
}
const result = getTitles(5);
console.log(result);// [ '首页', '刊登管理', '刊登设置' ]
</script>
    
</body>
</html>